package com.capacitydorm.server.service;

import com.capacitydorm.server.common.vo.*;
import com.capacitydorm.server.dao.*;
import com.capacitydorm.server.domain.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class LogService {

    @Resource
    private LogMapper logMapper;

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private DormMapper dormMapper;

    @Resource
    private TowerMapper towerMapper;

    @Resource
    private FloorMapper floorMapper;

    public PagesVo findLogs(Integer page, Integer rows) {
        PageHelper.startPage(page, rows);
        List<LogVo> logVos = new ArrayList<>();
        List<Log> logs = logMapper.selectAll();
        for (Log l : logs) {
            LogVo logVo = new LogVo(l.getId(), l.getAbsentnum(), l.getAbsentids());
            Date alltime = l.getTime();
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            DateFormat dateFormat1 = new SimpleDateFormat("hh:mm:ss");
            String date = dateFormat.format(alltime);
            String time = dateFormat1.format(alltime);
            logVo.setDate(date);
            logVo.setTime(time);
            logVos.add(logVo);
        }
        PageInfo<LogVo> info = new PageInfo<>(logVos);
        return new PagesVo(info.getPages(), info.getList());
    }

    public LogStudentsVo findStudentList(Integer id) {
        LogStudentsVo logStudentsVo = new LogStudentsVo();
        Log log = logMapper.selectByPrimaryKey(id);

        Date time = log.getTime();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = dateFormat.format(time);

        ArrayList<LogStudentVo> students = new ArrayList<>();
        String[] split = log.getAbsentids().split(",");
        for (int i = 0; i < split.length; i++) {
            Student student = studentMapper.selectByPrimaryKey(Integer.parseInt(split[i]));
            Dorm dorm = dormMapper.selectByPrimaryKey(student.getDormId());
            Floor floor = floorMapper.selectByPrimaryKey(dorm.getFloorId());
            Tower tower = towerMapper.selectByPrimaryKey(floor.getTowerId());
//            student.setDormName(dorm.getNumber());
//            student.setTowerName(tower.getName());
            LogStudentVo logStudentVo = new LogStudentVo(student.getName(), dorm.getNumber(), tower.getName());

            students.add(logStudentVo);
        }
        logStudentsVo.setStudents(students);
        logStudentsVo.setDate(date);
        return logStudentsVo;
    }
}
